package com.local.admin.controller;

import com.local.admin.constants.AdminConstants;
import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.constants.MallCategoryLevelEnum;
import com.local.common.util.ResultUtil;
import com.local.goods.feign.GoodsServiceFeign;
import com.local.goods.pojo.Goods;
import com.local.goods.pojo.GoodsCategory;
import com.local.goods.pojo.GoodsListRequestParam;
import com.local.goods.pojo.GoodsStatusRequestParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 商品管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/admin/goods")
public class AdminGoodsController {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    /**
     * 商品管理列表页面
     * @param request
     * @return
     */
    @GetMapping
    public String index(HttpServletRequest request) {
        request.setAttribute("path", "goods");
        return "admin/goods";
    }


    /**
     * 查询商品列表，支持翻页
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public ResultUtil list(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit,
                           @RequestParam("sidx") String sort, @RequestParam("order") String order,
                           @RequestParam(name = "goodsName", required = false) String goodsName,
                           @RequestParam(name = "goodsSellStatus", required = false) Integer goodsSellStatus) {
        page = Objects.isNull(page) || page.toString().isEmpty() ? 1 : page;
        limit = Objects.isNull(limit) || limit.toString().isEmpty() ? 10 : limit;
        sort = Objects.isNull(sort) || sort.isEmpty() ? "goods_id" : sort;
        order = Objects.isNull(order) || order.isEmpty() ? "desc" : order;
        GoodsListRequestParam requestParam = new GoodsListRequestParam(
                page, limit, sort, order, goodsName, goodsSellStatus);
        ResultUtil listResult = goodsServiceFeign.goodsList(requestParam);
        return listResult;
    }


    /**
     * 新增页面
     * @return
     */
    @GetMapping("/edit")
    public String add(HttpServletRequest request) {
        //一级分类
        ResultUtil firstLevelResult = goodsServiceFeign.categoryListForSelect(0);
        if (firstLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> firstLevelCategoryListResult = (Map<String, List<GoodsCategory>>) firstLevelResult.getData();
        List<GoodsCategory> firstLevelCategories = firstLevelCategoryListResult.get("goodsCategories");

        //二级分类
        ResultUtil secondLevelResult = goodsServiceFeign.categoryListForSelect(firstLevelCategories.get(0).getCategoryId());
        if (secondLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> secondLevelCategoryListResult = (Map<String, List<GoodsCategory>>) secondLevelResult.getData();
        List<GoodsCategory> secondLevelCategories = secondLevelCategoryListResult.get("goodsCategories");

        //三级分类
        ResultUtil thirdLevelResult = goodsServiceFeign.categoryListForSelect(secondLevelCategories.get(0).getCategoryId());
        if (thirdLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> thirdLevelCategoryListResult = (Map<String, List<GoodsCategory>>) thirdLevelResult.getData();
        List<GoodsCategory> thirdLevelCategories = thirdLevelCategoryListResult.get("goodsCategories");

        request.setAttribute("firstLevelCategories", firstLevelCategories);
        request.setAttribute("secondLevelCategories", secondLevelCategories);
        request.setAttribute("thirdLevelCategories", thirdLevelCategories);
        request.setAttribute("path", "goods-edit");
        request.setAttribute("content", "");
        return "admin/goods_edit";
    }


    /**
     * 新增商品
     * @param goods
     * @param session
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public ResultUtil save(@RequestBody Goods goods, HttpSession session) {
        Integer adminUserId = Integer.valueOf(session.getAttribute(AdminConstants.ADMIN_USER_ID_SESSION_KEY).toString());
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setCreateUser(adminUserId);
        goods.setUpdateUser(adminUserId);
        goods.setCreateTime(dateTime);
        goods.setUpdateTime(dateTime);

        ResultUtil saveResult = goodsServiceFeign.goodsSave(goods);
        return saveResult;
    }


    @GetMapping("/edit/{goodsId}")
    public String edit(@PathVariable("goodsId") Integer goodsId, HttpServletRequest request) {
        request.setAttribute("path", "edit");

        //查询商品
        ResultUtil<Goods> goodsResult = goodsServiceFeign.getGoodsById(goodsId);
        if (goodsResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Goods goods = goodsResult.getData();

        //
        ResultUtil<GoodsCategory> goodsCategoryLevelThreeResult = goodsServiceFeign.getCategoryById(goods.getGoodsCategoryId());
        if (goodsCategoryLevelThreeResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), goodsCategoryLevelThreeResult.getMessage());
        }
        GoodsCategory goodsCategoryLevelThree = goodsCategoryLevelThreeResult.getData();

        //
        ResultUtil<GoodsCategory> goodsCategoryLevelTwoResult = goodsServiceFeign.getCategoryById(goodsCategoryLevelThree.getParentId());
        if (goodsCategoryLevelTwoResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), goodsCategoryLevelTwoResult.getMessage());
        }
        GoodsCategory goodsCategoryLevelTwo = goodsCategoryLevelTwoResult.getData();

        //
        ResultUtil<GoodsCategory> goodsCategoryLevelOneResult = goodsServiceFeign.getCategoryById(goodsCategoryLevelTwo.getParentId());
        if (goodsCategoryLevelOneResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), goodsCategoryLevelOneResult.getMessage());
        }
        GoodsCategory goodsCategoryLevelOne = goodsCategoryLevelOneResult.getData();


        //一级分类
        ResultUtil firstLevelResult = goodsServiceFeign.categoryListForSelect(0);
        if (firstLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> firstLevelCategoryListResult = (Map<String, List<GoodsCategory>>) firstLevelResult.getData();
        List<GoodsCategory> firstLevelCategories = firstLevelCategoryListResult.get("goodsCategories");

        //二级分类
        ResultUtil secondLevelResult = goodsServiceFeign.categoryListForSelect(goodsCategoryLevelOne.getCategoryId());
        if (secondLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> secondLevelCategoryListResult = (Map<String, List<GoodsCategory>>) secondLevelResult.getData();
        List<GoodsCategory> secondLevelCategories = secondLevelCategoryListResult.get("goodsCategories");

        //三级分类
        ResultUtil thirdLevelResult = goodsServiceFeign.categoryListForSelect(goodsCategoryLevelTwo.getCategoryId());
        if (thirdLevelResult.getCode() != 200) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "请求失败，请稍后再试");
        }
        Map<String, List<GoodsCategory>> thirdLevelCategoryListResult = (Map<String, List<GoodsCategory>>) thirdLevelResult.getData();
        List<GoodsCategory> thirdLevelCategories = thirdLevelCategoryListResult.get("goodsCategories");


        request.setAttribute("firstLevelCategories", firstLevelCategories);
        request.setAttribute("secondLevelCategories", secondLevelCategories);
        request.setAttribute("thirdLevelCategories", thirdLevelCategories);
        request.setAttribute("firstLevelCategoryId", goodsCategoryLevelOne.getCategoryId());
        request.setAttribute("secondLevelCategoryId", goodsCategoryLevelTwo.getCategoryId());
        request.setAttribute("thirdLevelCategoryId", goodsCategoryLevelThree.getCategoryId());

        request.setAttribute("goods", goods);
        request.setAttribute("content", goods.getGoodsDetailContent());
        request.setAttribute("path", "goods-edit");

        log.info("goods-edit");

        return "admin/goods_edit";
    }


    /**
     * 修改
     * 注意：商品下架的时候，要检查商品是否在首页的推荐栏目中
     * @param goods
     * @param session
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public ResultUtil update(@RequestBody Goods goods, HttpSession session) {
        Integer adminUserId = Integer.valueOf(session.getAttribute(AdminConstants.ADMIN_USER_ID_SESSION_KEY).toString());
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        goods.setUpdateUser(adminUserId);
        goods.setUpdateTime(dateTime);
        ResultUtil updateResult = goodsServiceFeign.goodsUpdate(goods);
        return updateResult;
    }


    /**
     * 上架和下架
     * @param ids
     * @param session
     * @return
     */
    @PutMapping("/status/{goodsSellStatus}")
    @ResponseBody
    public ResultUtil status(@PathVariable("goodsSellStatus") Integer goodsSellStatus, @RequestBody Integer[] ids, HttpSession session) {
        Integer updateUserId = Integer.valueOf(session.getAttribute(AdminConstants.ADMIN_USER_ID_SESSION_KEY).toString());
        String updateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        GoodsStatusRequestParam requestParam = new GoodsStatusRequestParam(ids, goodsSellStatus, updateUserId, updateTime);
        ResultUtil statusResult = goodsServiceFeign.goodsStatus(requestParam);
        return statusResult;
    }
}
